# coding:utf-8
'''
Created on 2013-11-2

@author: song
'''
import os
import _winreg
import zipfile
import win32api
import time

def Delete(src):
	try:
		if os.path.exists(src):
			os.unlink(src)	
	except:
		pass

def DeleteFolder(src, deleteFolder=True):
	'''delete files and folders'''
	if os.path.isfile(src):
		try:
			os.remove(src)
		except:
			pass
	elif os.path.isdir(src):
		for item in os.listdir(src):
			itemsrc = os.path.join(src, item)
			DeleteFolder(itemsrc, True) 
		try:
			if deleteFolder:
				os.rmdir(src)
		except:
			pass
		
def CopyDir(src, dst):
	try:
		import shutil
		shutil.copytree(src, dst)
	except:
		pass

def Copy( src, dst ):
	# 拷贝文件
	try:
		import shutil
		if os.path.isfile( src ):
			shutil.copy(src,dst)
	except:
		pass

def DeleteSogouFiles():
	# 删除本地文件
	appdata = os.getenv("appdata")
	DeleteFolder(appdata + r"\SogouExplorer\DailyBackup")
	Delete(appdata + r"\SogouExplorer\Bin\SogouConf0")
	Delete(appdata + r"\SogouExplorer\Bin\SogouConf1")
	Delete(appdata + r"\SogouExplorer\Bin\SogouConf2")
	Delete(appdata + r"\SogouExplorer\Bin\SogouConf3")	
	Delete(appdata + r"\SogouExplorer\Misc.db")	

def DeleteLiteUpdateReg():
	# 删除注册表
	ExtensionRecommnedKey = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\SogouExplorer\ti", 0, _winreg.KEY_ALL_ACCESS )
	_winreg.DeleteValue( ExtensionRecommnedKey, r"LiteUpdate" )

def UnzipSogouConfFiles():
	# 解压SogouConf文件
	appdata = os.getenv( "appdata" )
	SogouConf = appdata + r"\SogouExplorer\Bin"
	homedir = os.getcwd()
	CopyDir( SogouConf, homedir )
	Copy( appdata + r"\SogouExplorer\Bin\SogouConf0", homedir + "\\sogouconf0" )
	Copy( appdata + r"\SogouExplorer\Bin\SogouConf1", homedir + "\\sogouconf1" )
	Copy( appdata + r"\SogouExplorer\Bin\SogouConf2", homedir + "\\sogouconf2" )
	Copy( appdata + r"\SogouExplorer\Bin\SogouConf3", homedir + "\\sogouconf3" )
	DeleteFolder( homedir + r"\ext" )
	os.mkdir( homedir + r"\ext" )
	s = r"SogouConfBuilder.exe -extract 11" + " " + homedir + " " + homedir + r"\ext"
	os.system( s )
	
def unzip(zip_path,save_path):
	zipfile.ZipFile(zip_path).extractall(save_path)
	
def getRecommendation_resource():
	homedir = os.getcwd()
	Recommendation_resource_File = homedir + r"\ext\recommendation_resource.zip" 
	zipTo = homedir + r"\ext\recommendation_resource"
	unzip( Recommendation_resource_File, zipTo )
	
# 读取文件内容
def getRecommendRule():
	homedir = os.getcwdu()
	RecommendRuleFile = homedir + r"\ext\recommendation_resource\recommend"
	if ( os.path.exists( RecommendRuleFile ) ):
		f = open( RecommendRuleFile )
		contentArray = f.read()
		contentStr = str( contentArray ).decode( 'utf-8' )
		print contentStr
	f.close()

def GetWinDir():
	return os.getenv( "WINDIR" )

def GetHost():
	return GetWinDir() + r"\system32\drivers\etc\hosts"

def AddHost( ip, domain ):
#  	import string
	host = GetHost()
	if ( os.path.exists( host ) ):
		f = open( host )
		contentArray = f.read()
	contentStr = str( contentArray ).splitlines()
	# print contentStr
	f.close()
	a = str( ip ) + "\t" + str( domain )
	if a in contentStr:
		return
	else:
		# print "a not in content"
		f1 = open( host )
		contentArrayB = f1.readlines()
		contentArrayB.append( str( ip ) + "\t" + str( domain ) )
		f1 = open( host, 'w' )
		for line in contentArrayB:
			f1.write( line.strip() + "\n" )
			f1.close()
			return True
		else:
			return False

def DelHost( domain, ip = "" ):
	'''
	| ##@函数目的: 删除一个域名为domain的host
	| ##@参数说明：domain：域名
	| ##@参数说明：ip：与域名对应的ip
	| ##@返回值：
	| ##@函数逻辑：从hosts文件中查找包含domain的行，并进行删除
	'''
	host = GetHost()
	if ( os.path.exists( host ) ):
		f = open( host )
		contentArray = []
		for line in f:
			oriLine = line.rstrip( ' ' ).rstrip( '\t' ).strip()
			if ( not oriLine.startswith( "#" ) ) and oriLine.find( str( domain ) ) != -1:
				# 不保留该行
				continue
			else:
				contentArray.append( line )
		f.close()
		f = open( host, 'w' )
		for line in contentArray:
			f.write( line.strip() + os.linesep )
		f.close()
		return True
	else:
		return False

def StartSELite( sePath ):
	'''
	| ##@函数目的: 启动搜狗浏览器
	| ##@参数说明：
	| ##@返回值：无
	| ##@函数逻辑：从注册表获取浏览器路径并启动
	'''
	global g_SEPath
	if sePath == "":
		seInstallReg = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r"Software\SogouExplorer", 0, _winreg.KEY_ALL_ACCESS )
		SogouExplorerPath = _winreg.QueryValueEx( seInstallReg, "" )[0]
		g_SEPath = SogouExplorerPath + "\\SogouExplorer.exe"
	else:
		g_SEPath = sePath
	if type( g_SEPath ) == unicode:
		g_SEPath = g_SEPath.encode( "gbk" )
	win32api.WinExec( g_SEPath )
# 	win32api.WinExec( "sogouexplorer.exe" )

if __name__ == '__main__':
# 	AddHost( "10.14.129.224", "athena.ie.sogou.com" )
		
# 	DeleteSogouFiles()
# 	DeleteLiteUpdateReg()
	StartSELite( "" )
	time.sleep( 30 )
# 	UnzipSogouConfFiles()
# 	getRecommendation_resource()
# 	getRecommendRule()
# 	DelHost( "athena.ie.sogou.com" )
	
	
